<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">用户管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!console">首页</a>
          <a><cite>用户管理</cite></a>
        </span>
    </div>
    <div class="layui-card-body">
        <div class="layui-form toolbar usertoolbar">
            搜索：
            <select id="user-search-key">
                <option value="username">-请选择-</option>   
                <option value="username">账号</option>
                <option value="mobile">手机号</option>
            </select>&emsp;
            <input id="user-search-value" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
            <button id="user-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
            
        <!--     <button id="user-btn-export" class="layui-btn icon-btn"><i class="layui-icon">&#xe601;</i>导出</button>
            <button type="button" class="layui-btn" id="user-btn-import">
                <i class="layui-icon">&#xe67c;</i>导入
            </button> -->
        </div>

        <table class="layui-table" id="user-table" lay-filter="user-table"></table>
    </div>
</div>


<!-- 表格操作列 -->
<script type="text/html" id="user-table-bar">
 {{#  if(admin.hasPerm("sys:sysuser:update") ){   }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-xs" lay-event="reset">重置密码</a>
 {{#     } }} 
 {{#  if(admin.hasPerm("sys:sysuser:delete") ){   }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
 {{#     } }} 
</script>

<!-- 表格状态列 -->
<script type="text/html" id="user-tpl-state">
    {{#  if(admin.hasPerm("sys:sysuser:update") ){   }}
    <input type="checkbox" lay-filter="user-tpl-state" value="{{d.userId}}" lay-skin="switch" lay-text="正常|锁定"   {{d.status==1?'checked':''}}/>
 {{#     } }} 
</script>

<script type="text/html" id="usertoolbar">
     {{#  if(admin.hasPerm("sys:sysuser:save")){ }}
     <button id="user-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
     {{#     } }} 
 
</script>

<script type="text/html" id="userType">
    {{#    if(d.businessId==0){ }}
    <button type="button" class="layui-btn layui-btn-normal layui-btn-xs layui-btn-radius">管理员</button>
    {{#     }else if(d.roles)  { d.roleNams=null; d.roles.forEach(function(n){ d.roleNams=(d.roleNams&&n.roleName?(d.roleNams+","):"")+n.roleName;}) }}
    <button type="button" class="layui-btn layui-btn-warm layui-btn-xs layui-btn-radius">{{d.roleNams||''}}</button>
    {{#     } }}
</script>

<script>
   var admin;

    layui.use(['form', 'table', 'util', 'config', 'admin', 'upload','laytpl','element' ], function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
          admin = layui.admin;
        
        //上传
        var upload = layui.upload;
        let laytpl = layui.laytpl;
        let element = layui.element;
        var business = admin.getTempData('t_business');
        var where="";
        var businessId=null;
         if(business!=null&&business!=undefined){
        	 where="?businessId="+business.id;
             businessId=business.id;
             admin.putTempData('t_business', null);
         }else{

         }
        // 渲染表格
        table.render({
            elem: '#user-table',
            url: config.base_server + 'sys/sysuser/list'+where,
            method: 'GET',
            id:"user-table",
            page: true,
            cols: [[
                {type: 'numbers'},
            
                {field: 'username',   title: '账号'},
         
                {field: 'mobile',   title: '手机号'},
                {fixed: 'right', align: 'center', title: "角色"   ,  toolbar:"#userType" },
                {
                      templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, title: '创建时间'
                },
                {field: 'status',  templet: '#user-tpl-state', title: '状态'},
                {fixed: 'right', align: 'center', toolbar: '#user-table-bar', title: '操作', width: 175}
            ]]
        });
        
        laytpl($("#usertoolbar")[0].innerHTML).render({ }, function(html){
			  $(".layui-card-body .usertoolbar").append(html);
			  element.render('nav');
			  element.render('select');
			  element.render();
		  });
       
        // 添加按钮点击事件
        $('#user-btn-add').click(function (e) {
        	console.log(e)
            showEditUserModel();
        });

        // 工具条点击事件
        table.on('tool(user-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { // 修改
             
            	showEditUserModel(data);
            } else if (layEvent === 'reset') { // 重置密码
                layer.confirm('确定重置此用户的密码吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('sys/'+obj.data.userId+'/password', {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 500});
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 500});
                        }
                    }, 'PUT');
                });
            } else if (layEvent === 'del') { // 删除
                layer.confirm('确定删除此用户吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('sys/sysuser/user/'+obj.data.userId, {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 500});
                            table.reload('user-table', {});
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 500});
                        }
                    }, 'delete');
                });
            }
        });

        //显示表单弹窗
        var showEditUserModel = function (data) {
        	  var title = data ? '修改用户' : '添加用户';
            //修改sex值
            if (data){
             //   data.sex = data.sex+'';
                data.method="update"
            }else{
            	data={method:"save"};
            }
            element.render();
            if(businessId)data.businessId=businessId;
            admin.putTempData('t_user', data);
            editUserindex=   layer.open({
                    type: 1,
                    title: title,
                    // skin: 'layui-layer-rim', //加上边框
                    area: ['400px', '300px'], //宽高
                    offset: '60px',//距顶部
                    scrollbar: false,//是否允许浏览器出现滚动条
                    // btn: ['保存'],
                    maxmin: true,//开启最大化按钮
                   // content: 'pages/system/user_form.html',
                    success:function(layero, index){
                         console.log(index)
                    	  $(layero).children('.layui-layer-content').load('pages/system/user_form.html');
                    	  admin.putTempData('editUserindex', index);
                    	  //businessId
                    	  admin.table=table;
                    }
                })
          /*   admin.popupCenter({
                title: title,
                path: 'pages/system/user_form.html',
                finish: function () {
                    table.reload('user-table', {});
                }
            }); */
        };

        // 搜索按钮点击事件
        $('#user-btn-search').click(function () {
            var key = $('#user-search-key').val();
            var value = $('#user-search-value').val();
            table.reload('user-table', {where: {searchKey: key, searchValue: value}});
        });

        // 导出
        $('#user-btn-export').click(function () {
            var url = config.base_server + 'sys/sysuser/export';
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = "blob";
            xhr.setRequestHeader("client_type", "DESKTOP_WEB");
           
            xhr.onload = function() {
                if (this.status == 200) {
                    var fileName = "user.xlsx";
                    var blob = this.response;
                    var a = document.createElement('a');
                    a.innerHTML = fileName;
                    // 指定生成的文件名
                    a.download = fileName;
                    a.href = URL.createObjectURL(blob);
                    document.body.appendChild(a);
                    var evt = document.createEvent("MouseEvents");
                    evt.initEvent("click", false, false);
                    a.dispatchEvent(evt);
                    document.body.removeChild(a);
                }
            }
            xhr.send();
        });

        // 修改user状态
        form.on('switch(user-tpl-state)', function (obj) {
          layer.confirm('该操作将会踢登陆用户下线！确定继续吗？', function (i) {
            layer.close(i);
            layer.load(2);
          
            admin.req('sys/sysuser/update',JSON.stringify( {
                userId: obj.elem.value,
                status: obj.elem.checked ? 1 : 0
            }), function (data) {
                layer.closeAll('loading');
                if (data.code == 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                  //  table.reload('user-table', {});
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                 
                }
                table.reload('user-table', {});
            }, 'POST');
          }, function (x) {
        	 
        	  table.reload('user-table', {});
          })
          form.render('checkbox');
        });

        //上传
        var importUrl = config.base_server + 'sys/sysuser/import';
        upload.render({
            elem: '#user-btn-import'
            ,url: importUrl
            ,accept: 'file' //普通文件
            ,multiple: false
          
            ,done: function(data){
                if (data.code == 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                    table.reload('user-table', {});
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                }
            }
        });

      
    });
</script>